Android ImageView 원 각 효과 그리 기
안 드 로 이 드 개발 에서 우 리 는 항상 그림 의 원형/원 각 효 과 를 실현 해 야 한다.우 리 는 두 가지 방식 으로 이런 효 과 를 실현 할 수 있다.하 나 는 Xfermode 를 사용 하고 다른 하 나 는 BitmapShader 를 사용 하여 이 루어 집 니 다.다음은 이 두 가지 용법 을 각각 소개 하 겠 습 니 다.
Xfermode 방식 으로 구현
이 방식 의 핵심 코드 를 사용 하면 다음 과 같 습 니 다.
private Bitmap creataBitmap(Bitmap bitmap) {
// Bitmap
Bitmap target = Bitmap.createBitmap(1000,1000, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
final Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setAntiAlias(true);
//
canvas.drawCircle(500,500,500,paint);
// Xfermode, SRC_IN ,
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// bitmap
canvas.drawBitmap(bitmap,0,0,paint);
return target;
}
위 코드 에 서 는 지 정 된 캔버스 에 두 겹 의 그림 이 그 려 져 있 음 을 알 수 있 습 니 다.하 나 는 반경 500 픽 셀 의 원형 이 고,하 나 는 대상 비트 맵 을 위 에 그 리 는 것 입 니 다.paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)도 호출 되 었 습 니 다.IN));역할 은 이 두 개의 효과 도 를 중첩 한 후 두 번 째 그림 의 교 집합 도 를 얻 는 것 이다.그래서 우 리 는 먼저 원형 을 그린 다음 에 Bitmap 를 그리고 원형 으로 교차 하 며 꺼 낸 것 이 바로 원형 구역 의 Bitmap 입 니 다.Porter Duff.Mode 에는 모두 16 가지 효과 가 있 습 니 다.다음 과 같 습 니 다.
모드 에 따라 표시 되 는 효과 도 를 제어 할 수 있 습 니 다.
적용 시작
1.사용자 정의 속성 은 attrs.xml 에 있 습 니 다.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="borderRadius" format="dimension" />
<attr name="type">
<enum name="circle" value="0"/>
<enum name="round" value="1"/>
</attr>
<attr name="src" format="reference"/>
<declare-styleable name="RoundImageView">
<attr name="borderRadius"/>
<attr name="type"/>
<attr name="src"/>
</declare-styleable>
</resources>
2.사용자 정의 뷰
public class RoundImageView extends View {
private int type;
private static final int TYPE_CIRCLE = 0;
private static final int TYPE_ROUND = 1;
//
private Bitmap mSrc;
//
private int mRadius;
//
private int mWidth;
//
private int mHeight;
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
//
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RoundImageView);
//
int count = a.getIndexCount();
for (int i=0 ; i<count ; i++){
int attr = a.getIndex(i);
switch (attr){
case R.styleable.RoundImageView_borderRadius:
int defValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10f,getResources().getDisplayMetrics());
mRadius = a.getDimensionPixelSize(attr, defValue);
break;
case R.styleable.RoundImageView_type:
type = a.getInt(attr,0);
break;
case R.styleable.RoundImageView_src:
mSrc = BitmapFactory.decodeResource(getResources(),a.getResourceId(attr,0));
break;
}
}
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//
int specMode = MeasureSpec.getMode(widthMeasureSpec);
int specSize = MeasureSpec.getSize(widthMeasureSpec);
if (specMode == MeasureSpec.EXACTLY){
mWidth = specSize;
}else {
int desireByImg = getPaddingLeft() + getPaddingRight() + mSrc.getWidth();
if (specMode == MeasureSpec.AT_MOST)// wrap_content
{
mWidth = Math.min(desireByImg, specSize);
} else
mWidth = desireByImg;
}
//
specMode = MeasureSpec.getMode(heightMeasureSpec);
specSize = MeasureSpec.getSize(heightMeasureSpec);
if (specMode == MeasureSpec.EXACTLY){
mHeight = specSize;
}else {
int desire = getPaddingTop() + getPaddingBottom() + mSrc.getHeight();
if (specMode == MeasureSpec.AT_MOST)// wrap_content
{
mHeight = Math.min(desire, specSize);
} else
mHeight = desire;
}
setMeasuredDimension(mWidth,mHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
switch (type){
case TYPE_CIRCLE:
int min = Math.min(mWidth,mHeight);
// Bitmap, Bitmap。
mSrc = Bitmap.createScaledBitmap(mSrc, min, min, false);
canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null);
break;
case TYPE_ROUND:
mSrc = Bitmap.createScaledBitmap(mSrc, mWidth, mHeight, false);
canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null);
break;
}
}
/**
*
* @param source
* @return
*/
private Bitmap createRoundConerImage(Bitmap source) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
RectF rect = new RectF(0, 0, mWidth, mHeight);
canvas.drawRoundRect(rect, mRadius, mRadius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
/**
*
* @param source
* @param min
* @return
*/
private Bitmap createCircleImage(Bitmap source, int min) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.drawCircle(min/2,min/2,min/2,paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
}
3.레이아웃 파일
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:roundview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context="mo.yumf.com.myviews.MainActivity">
<mo.yumf.com.myviews.RoundImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="20dp"
roundview:borderRadius="10dp"
roundview:src="@drawable/ac_default_icon"
roundview:type="round"/>
<mo.yumf.com.myviews.RoundImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="20dp"
roundview:src="@drawable/ac_default_icon"
roundview:type="circle"/>
</LinearLayout>
위의 사용자 정의 View 에는 레이아웃 에 불 러 올 그림 자원 만 설정 할 수 있 고 코드 에 그림 을 설정 할 수 없 는 한계 가 있 습 니 다.다음 과 같은 방식 으로 사용자 정의 ImageView 를 선택 합 니 다.
public class RoundImageView extends ImageView {
private int type;
private static final int TYPE_CIRCLE = 0;
private static final int TYPE_ROUND = 1;
//
private Bitmap mSrc;
//
private int mRadius;
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
//
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RoundImageView);
//
int count = a.getIndexCount();
for (int i=0 ; i<count ; i++){
int attr = a.getIndex(i);
switch (attr){
case R.styleable.RoundImageView_borderRadius:
int defValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10f,getResources().getDisplayMetrics());
mRadius = a.getDimensionPixelSize(attr, defValue);
break;
case R.styleable.RoundImageView_type:
type = a.getInt(attr,0);
break;
}
}
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() != null){
Bitmap bitmap = getBitmap(getDrawable());
if (bitmap != null){
switch (type){
case TYPE_CIRCLE:
// ImageView ,
int min = Math.min(getMeasuredWidth(),getMeasuredHeight());
// Bitmap, Bitmap。
mSrc = Bitmap.createScaledBitmap(bitmap, min, min, false);
canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null);
break;
case TYPE_ROUND:
mSrc = Bitmap.createScaledBitmap(bitmap, getMeasuredWidth(), getMeasuredHeight(), false);
canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null);
break;
}
}
}else {
super.onDraw(canvas);
}
}
private Bitmap getBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable){
return ((BitmapDrawable)drawable).getBitmap();
}else if (drawable instanceof ColorDrawable){
Rect rect = drawable.getBounds();
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
int color = ((ColorDrawable)drawable).getColor();
Bitmap bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawARGB(Color.alpha(color),Color.red(color), Color.green(color), Color.blue(color));
return bitmap;
}else {
return null;
}
}
/**
*
* @param source
* @return
*/
private Bitmap createRoundConerImage(Bitmap source) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
RectF rect = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight());
canvas.drawRoundRect(rect, mRadius, mRadius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
/**
*
* @param source
* @param min
* @return
*/
private Bitmap createCircleImage(Bitmap source, int min) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.drawCircle(min/2,min/2,min/2,paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[Swift] TableViewCell에 ImageView를 추가하여 URL에 지정된 이미지를 표시합니다.추가 UIIMageView에 이미지 먼저 표시 json에서 가져온 URL로 이미지 표시 Xcode Main을 엽니다.스토리보드에서 TableVIewCell에 UIimageView를 추가합니다.디자인을 함께 수정하여 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.